let fs = require('fs');

class TextDb {

    constructor(){
        var d = new Date();
        var curMonth = d.getMonth() + 1;
        curMonth = curMonth >= 10 ? curMonth.toString() : '0' + curMonth.toString();
        this.curMonth = d.getFullYear().toString() + curMonth;

        this.dbGroup = 'default';
    }

    setMonth(month){
        this.curMonth = month;
    }

    setDb(dbGroup){
        this.dbGroup = dbGroup;
    }

    getDbPath(){
        var dbPath = __dirname + "/../db/data_" + this.dbGroup + "_" + this.curMonth + ".db";
        return dbPath;
    }

    //保存数据
    async push(data){
        var DbData = [];
        var dbPath = this.getDbPath();

        if(fs.existsSync(dbPath)){
            var curDataStr = fs.readFileSync(dbPath);
            
            DbData = JSON.parse(curDataStr);
        }
        
        DbData.push(data);
        fs.writeFileSync(dbPath, JSON.stringify(DbData));
    }

    //获取数据
    async getData(){

        var DbData = [];
        var dbPath = this.getDbPath();
        
        if(fs.existsSync(dbPath)){
            var curDataStr = fs.readFileSync(dbPath);
            DbData = JSON.parse(curDataStr);
        }
        
        //按时间倒序输出
        DbData.sort((a,b) =>{
            return b.time - a.time
        });

        return DbData;
    }
}
module.exports = new TextDb();